// pages/news/service/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    maxId: null,
    minId: null,
    searchMinId: null,
    end: false,
    isSearch: false,
    saveData: [],
    listData: [],
    page: 1,
    total: 1,
    pageStatus: false,
    msg: '',
    userInfo: {},
    // autosize:{minHeight: 0}
    autosize: {
      minHeight: 20
    },
    isSend: false,
    send: true, //发送中 发送按钮 显示loading
    chatUUID: '',
    timer: null,
    nav_scroll_height: 0,
    scrollViewHeight: 0,
    windowHeight: 0,
    toView: '',
    footer_bottom: 20,
    extendList: [{
        id: 1,
        img: '../../../image/news/extend1.png',
        txt: '图片'
      },
      {
        id: 2,
        img: '../../../image/news/extend2.png',
        txt: '拍照'
      }
    ],
    emojiShow: false,
    extendShow: false,
    emojiList: [
      "😀", "😁", "😂", "😃", "😄", "😅", "😆", "😉", "😊", "😋", "😎", "😍", "😘", "😗", "😙", "😚", "😇", "😐", "😑", "😶", "😏", "😣", "😥", "😮", "😯", "😪", "😫", "😴", "😌", "😛", "😜", "😝", "😒", "😓", "😔", "😕", "😲", "😷", "😖", "😞", "😟", "😤", "😢", "😭", "😦", "😧", "😨", "😬", "😰", "😱", "😳", "😵", "😡", "😠", "💪", "👈", "👉", "☝", "👆", "👇", "✌", "✋", "👌", "👍", "👎", "✊", "👊", "👋", "👏", "👐", '💀', '👻', '👽', '💣',
    ],
    cursor: 0,
    isUpper: false,
    isLower: false,
    sendData: {}, // 请求发送数据
    serveMobile: null, // 客服手机
    goodsImg: null, // 商品图片
    goodsContext: null, //商品描述
    serveMobile: null, // 客服手机
    shopShow: false, //显示商品
    valid: true, //节流阀 防多次点击发送
    flag: true, //判断是否在第一页
    hintShow: false, //提示显示
    pageno: "",
    positionId: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.cloud.init()
    wx.getSystemInfo({
      success: (res) => {
        console.log(res.windowHeight);
        this.setData({
          windowHeight: res.windowHeight,
        });
      }
    });
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    })
    // 
    let {
      chatUUID,
      showName,
      isSearch,
      mobile,
      img,
      context,
    } = options
    if (img && context) {
      this.setData({
        shopShow: true
      })
    }
    if (isSearch) {
      let {
        positionId,
        pageno,
        isSearch
      } = options
      this.setData({
        chatUUID,
        positionId,
        pageno,
        isSearch
      })
      console.log(chatUUID, positionId, pageno);
      this.getSearch()
      this.getminId() // 获取最新的id
    } else {
      if (chatUUID) {
        this.setData({
          chatUUID
        })
        this.getList()
        this.setTiming() //设置定时器
      } else {
        console.log('获取chatUUid');
        this.setData({
          "serveMobile": mobile,
          "goodsImg": img,
          "goodsContext": context,
        })
        this.getChatUUid()
      }

    }
    wx.setNavigationBarTitle({
      title: showName
    })
  },
  //根据uuid 获取消息列表 
  async getminId() {

    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      // "path": "/v1/chat/"+this.data.userInfo.mobile+"/" + chatUUID + '/' + this.data.page,
      "path": "/v1/chat/" + this.data.chatUUID + '/1',
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    if (code == 1) {
      if (data.data.chatList.length > 0) {
        let list = data.data.chatList.reverse()
        let searchMinId = list[list.length - 1].positionId
        this.setData({
          searchMinId,
          end: false
        })
      } else {
        console.log('没有新信息 不渲染');
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
    }
    this.setTiming()
  },
  // 根据客服手机号 和个人手机号 获取 chatuuid
  async getChatUUid(mobile) {

    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      // "path": "/v1/chat/serv/" + this.data.userInfo.mobile + "/" + this.data.serveMobile,
      "path": "/v1/chat/serv/" + this.data.serveMobile,
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    console.log(data, code, errorMsg, '获取chatuuid');
    if (code == 1) {
      if (data) {
        this.setData({
          chatUUID: data
        })
        this.getList()
        this.setTiming() //设置定时器
      } else {
        console.log('创建新会话');
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
    }
    this.setData({
      pageStatus: true
    });
  },


  //根据uuid 获取消息列表 
  async getList() {

    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      // "path": "/v1/chat/"+this.data.userInfo.mobile+"/" + chatUUID + '/' + this.data.page,
      "path": "/v1/chat/" + this.data.chatUUID + '/1',
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    console.log(data, code, errorMsg);
    if (code == 1) {
      if (data.data.chatList.length > 0) {
        let list = data.data.chatList.reverse()
        let arr = list.concat(list)
        this.setData({
          total: data.total,
        })
        console.log(list);

        // if (status) { // 触发搜索
        //   let listData = this.data.listData // 数据
        //   listData = listData.unshift(...list)
        //   this.setData({
        //     listData
        //   })
        // } else {
        let minId = list[list.length - 1].positionId
        let maxId = list[0].positionId

        this.setData({
          maxId,
          minId,
          // listData: arr
          listData: list,
          toView: 'msg-' + list[list.length - 1].positionId

        })
      } else {
        console.log('没有新信息 不渲染');
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
    }
    this.setData({
      pageStatus: true
    });
  },
  //根据uuid 获取消息列表 
  async getSearch() {

    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      // "path": "/v1/chat/"+this.data.userInfo.mobile+"/" + chatUUID + '/' + this.data.page,
      "path": "/v1/chat/" + this.data.chatUUID + '/1?minId=' + (this.data.positionId - 4) + '&maxId=' + (this.data.positionId - 0 + 4),

      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    console.log(data, code, errorMsg);
    if (code == 1) {
      if (data.data.chatList.length > 0) {
        let list = data.data.chatList.reverse()
        // let arr = list.concat(list)
        this.setData({
          total: data.total,
        })
        console.log(list);

        // if (status) { // 触发搜索
        //   let listData = this.data.listData // 数据
        //   listData = listData.unshift(...list)
        //   this.setData({
        //     listData
        //   })
        // } else {
        let minId = list[list.length - 1].positionId
        let maxId = list[0].positionId

        this.setData({
          maxId,
          minId,
          // listData: arr
          listData: list,
          flag: false

        })
        console.log(this.data.positionId, ' this.data.positionId');
        setTimeout(() => {
          this.setData({
            // toView: 'msg-' + this.data.positionId,
          })
        }, 200);
      } else {
        console.log('没有新信息 不渲染');
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })
    }
    this.setData({
      pageStatus: true
    });
  },

  emoji() {
    let toView = ''
    if (this.data.isSearch && !this.data.end) {
      this.setData({
        end: true
      })
      this.getList()
    } else {
      if (this.data.listData.length > 0) {
        toView = 'msg-' + this.data.listData[this.data.listData.length - 1].positionId
      }
    }
    this.setData({
      extendShow: false,
      emojiShow: true,
      flag: true,
      footer_bottom: 0,
      shopShow: false,
    })
    let _this = this
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('#footer').boundingClientRect();
      query.exec(function (res) {
        let height = res[0].height
        _this.setData({
          scrollViewHeight: _this.data.windowHeight - height - _this.data.footer_bottom
        })
        if (_this.data.listData.length > 0) {
          if (!_this.data.isSearch && _this.data.end) {
            setTimeout(() => {
              _this.setData({
                toView
              })
            }, 200);
          } else {
            _this.setData({
              toView
            })
          }
        }
      })
    })
  },
  imgPreview(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: [src] // 需要预览的图片http链接列表
    })
  },
  onChange(value) {
    // console.log(value);
  },
  add() {
    console.log('addClick');
    this.setData({
      extendShow: true,
      emojiShow: false,
      footer_bottom: 0,
      shopShow: false,
      flag: true,
    })
    let toView = ''
    if (this.data.isSearch && !this.data.end) {
      this.setData({
        end: true
      })
      this.getList()
    }
    if (this.data.listData.length > 0) {
      toView = 'msg-' + this.data.listData[this.data.listData.length - 1].positionId
    }

    setTimeout(() => {
      let _this = this
      const query = wx.createSelectorQuery();
      query.select('#footer').boundingClientRect();
      query.exec(function (res) {
        console.log(res);
        let height = res[0].height
        _this.setData({
          scrollViewHeight: _this.data.windowHeight - height - _this.data.footer_bottom,
        })
        // if (!_this.data.isSearch && _this.data.end) {
          if (_this.data.listData.length > 0) {
            setTimeout(() => {
              _this.setData({
                toView
              })
            }, 200);
          // }
        }
      })

    })
  },
  scrollClick() {
    this.setData({
      extendShow: false,
      emojiShow: false,
      footer_bottom: 20
    })
    let _this = this
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('#footer').boundingClientRect();
      query.exec(function (res) {
        console.log(res);
        let height = res[0].height
        _this.setData({
          scrollViewHeight: _this.data.windowHeight - height - _this.data.footer_bottom

        })
        // if (_this.data.listData.length > 0) {
        //   setTimeout(() => {
        //     _this.setData({
        //       toView
        //     })
        //   }, 100);

        // }
      })
    }, 200)

  },

  // srool view 滚动事件
  bindscroll(e) {
    // console.log(e.detail);
    // console.log(e.detail.scrollTop);

  },
  binddragend(e) {
    console.log(e);
    console.log(e.detail);
    console.log(e.detail.scrollTop);
    this.setData({
      scrollTop: e.detail.scrollTop
    })
  },
  focus(e) {
    if (this.data.isSearch && !this.data.end) {
      this.setData({
        end: true
      })
      this.getList()
    }
    let {
      cursor
    } = e.detail
    console.log(e.detail.height);
    this.setData({
      shopShow: false,
      isSend: true,
      cursor,
      extendShow: false,
      emojiShow: false,
      flag: true,
    })
    let windowHeight = wx.getSystemInfoSync().windowHeight;
    const query = wx.createSelectorQuery();
    query.select('#' + e.currentTarget.id).boundingClientRect();
    query.selectViewport().scrollOffset();
    console.log('keyBoardHeight', e.detail.height)
    var that = this;
    query.exec(function (res) {
      let inputBottom = windowHeight - res[0].bottom;
      //如果input没有被键盘遮挡，不做任何事
      if (!res[0] || e.detail.height <= inputBottom) {
        that.setData({
          nav_scroll_height: 0
        });
        console.log('没有遮挡');
        console.log(e.detail.height - inputBottom + 20, '键盘高度');
        return;
      }
      // that.setData({
      //   toView: ''
      // })
      console.log('遮挡', inputBottom);
      console.log(e.detail.height - inputBottom + 20, '键盘高度');
      let scrollViewHeight = that.data.windowHeight - e.detail.height + inputBottom - 20 - 72
      let toView = 'msg-' + that.data.listData[that.data.listData.length - 1].positionId
      console.log(scrollViewHeight, 'scrollViewHeight');
      console.log(toView, 'toView');
      //获取input被键盘遮挡的高度
      that.setData({
        nav_scroll_height: e.detail.height - inputBottom + 20,
        scrollViewHeight,
      });
      that.setData({
        toView
      })
      wx.pageScrollTo({ //滑动input被键盘遮挡的距离
        scrollTop: res[1].scrollTop + that.data.nav_scroll_height, //页面滚动的距离
        duration: 200 //页面滚动速度 单位ms
      });
    })
  },

  unfocus(e) {
    let {
      cursor
    } = e.detail
    // console.log(cursor,this.data.msg.length);
    // console.log(this.data.windowHeight);
    // console.log(this.data.msg[cursor - 1]);
    // let msg = this.data.msg.slice(cursor, '😂')
    console.log('失去焦点');
    if (this.data.send) {
      this.setData({
        isSend: false,
      })
    }
    this.setData({
      cursor,
      // isSend: false,
      flag: true,
      nav_scroll_height: 0,
      scrollViewHeight: this.data.windowHeight - 72,
    })
    if (this.data.listData && this.data.listData.length > 0) {
      this.setData({
        toView: 'msg-' + this.data.listData[this.data.listData.length - 1].positionId
      })
    }
  },
  linechange(e) {
    console.log('高度变化');
    let toView = ''
    if (this.data.listData.length > 0) {
      toView = 'msg-' + this.data.listData[this.data.listData.length - 1].positionId
    }
    let _this = this
    setTimeout(() => {
      const query = wx.createSelectorQuery();
      query.select('#footer').boundingClientRect();
      query.exec(function (res) {
        console.log(res);
        let height = res[0].height
        _this.setData({
          scrollViewHeight: _this.data.windowHeight - height - 20
        })
        console.log(_this.data.scrollViewHeight);
        if (_this.data.listData.length > 0) {
          setTimeout(() => {
            _this.setData({
              toView
            })
          }, 100);

        }
      })
    }, 200)
  },
  //方法：
  //soure 原字符串
  //start 位置
  //newStr 要插入的字符串
  insertStr(soure, start, newStr) {
    console.log(soure, start, newStr);
    return soure.slice(0, start) + newStr + soure.slice(start);
  },

  topevent(e) {
    console.log(this.data.isUpper);
    if (this.data.isUpper == true) {
      return
    }
    this.setData({
      isUpper: true,
      flag: false
    })
    wx.showToast({
      icon: 'loading',
      title: '正在加载中',
    })

    this.context(1, false, true)
  },

  btmevent(e) {
    // if (this.data.page == 1) {
    //   wx.hideToast(); //隐藏Toast
    //   return
    // }
    if (this.data.isLower == true) {
      return
    }
    this.setData({
      isLower: true,
      flag: true,
      hintShow: false
    })
    wx.showToast({
      icon: 'loading',
      title: '正在加载中',
    })

    this.context(2, false, true)
  },


  //根据id 获取消息上下文 flag 表示向下翻页 跳转到最后一个 flag2表示不跳转
  async context(type, flag, flag2) {
    // console.log('轮询');
    let path = ''
    if (type == 1) {
      path = '/v1/chat/' + this.data.chatUUID + '/1?' + "maxId=" + this.data.maxId
    } else {
      path = '/v1/chat/' + this.data.chatUUID + '/1?' + "minId=" + this.data.minId
    }
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      path,
      // "path": "/v1/chat/search/18511581997" + "/" + this.data.chatUUID,
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })

    // console.log(data, code, errorMsg);
    let id = this.data.minId
    let id2 = this.data.maxId
    if (code == 1) {
      if (data.data.chatList.length == 0) {
        // console.log('无消息');
        this.setData({
          flag: true
        })
        if (type == 2) {
          if (this.data.isSearch) {
            this.setData({
              // searchMinId: this.data.minId,
              end: true,
              flag: true
            })
          }
        }
      } else {
        let list = data.data.chatList.reverse()
        if (type == 1) {


          // let minId = list[list.length - 1].positionId
          let maxId = list[0].positionId
          let arr = list.concat(this.data.listData)
          this.setData({
            maxId,
            listData: arr,
            page: this.data.page + 1
          })
          if (flag2) {
            this.setData({
              toView: 'msg-' + id2
            })
          }
          console.log(this.data.toView);
        } else {
          console.log(this.data.toView, 'toview');

          let minId = list[list.length - 1].positionId
          let arr = this.data.listData.concat(list)
          this.setData({
            minId,
            listData: arr,
          })
          if (flag2) {
            this.setData({
              toView: 'msg-' + id
            })
            console.log(this.data.toView);
          } else {
            if (flag || this.data.flag) {
              console.log('跳转');
              setTimeout(() => {
                this.setData({
                  toView: 'msg-' + arr[arr.length - 1].positionId
                })
              }, 100);
              console.log(this.data.toView, 'toview');
            } else {
              console.log('  hintShow: true');
              this.setData({
                hintShow: true
              })
            }
          }
        }
      }
      wx.hideToast()
    } else {
      wx.showToast({
        icon: 'none',
        title: errorMsg
      })

    }
    if (!this.data.send) {
      this.setData({
        send: true,
        isSend: false
      })
    }
    if (type == 1) {
      this.setData({
        isUpper: false
      })
    } else {
      this.setData({
        isLower: false
      })
    }
  },
  async serchContext() {
    if (this.data.end) {
      this.setData({
        hintShow: false

      })
      return
    }
    let path = '/v1/chat/' + this.data.chatUUID + '/1?' + "minId=" + this.data.searchMinId
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      path,
      // "path": "/v1/chat/search/18511581997" + "/" + this.data.chatUUID,
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    if (this.data.end) {
      this.setData({
        hintShow: false

      })
      return
    }
    console.log(code, data, errorMsg);
    if (code == 1) {
      if (data.data.chatList.length == 0) {
        console.log('无新消息');
      } else {
        console.log(' hintShow: true');
        this.setData({
          hintShow: true
        })
        this.getNewList()
      }
    }
  },
  async getNewList() {
    let num = this.data.searchMinId - 10
    const {
      data: {
        code,
        errorMsg,
        data
      }
    } = await wx.cloud.callContainer({
      "config": {
        "env": "prod-0g38oh8hf0e4d5ac"
      },
      path: '/v1/chat/' + this.data.chatUUID + '/1?' + "minId=" + num,
      "header": {
        "X-WX-SERVICE": "springboot-069k"
      },
      "method": "get",
      "data": {
        "action": "inc"
      }
    })
    if (code == 1) {
      this.setData({
        saveData: data.data.chatList.reverse(),
      })
    }
  },
  hintClick() {
    this.setData({
      end: true,
      flag: true
    })
    if (!this.data.isSearch) {
      this.setData({
        toView: 'msg-' + this.data.minId,
        hintShow: false
      })
    } else {
      let minId = this.data.saveData[this.data.saveData.length - 1].positionId
      let maxId = this.data.saveData[0].positionId
      this.setData({
        listData: this.data.saveData,
        searchMinId: this.data.saveData[this.data.saveData.length - 1].positionId,
        hintShow: false,
        maxId,
        minId
      })
      setTimeout(() => {
        this.setData({
          toView: 'msg-' + this.data.searchMinId,
        })
      }, 200);
    }
  },
  closeShop() {
    this.setData({
      shopShow: false
    })
  },
  sendGoods() {
    this.send(3)

  },
  sendTxt() {
    if (!this.data.valid) { // 首次点击不会return,   
      return;
    }
    // 首次点击之后全局变量置为false,同时向下执行，setTimeout推入待执行队列
    if (!this.data.msg) {
      wx.showToast({
        title: '不能发送空白消息',
        icon: 'none'
      })
      return
    }
    this.data.valid = false;
    this.setData({
      send: false
    })
    this.send(1)
    setTimeout(() => {
      console.log('按钮点击');
      this.data.valid = true; // 在定时器未执行前，valid为false,所以点击方法会直接return
    }, 1000)
  },
  // moji 下的发送 删除
  sendtxt1() {
    if (!this.data.valid) { // 首次点击不会return,   
      return;
    }
    // 首次点击之后全局变量置为false,同时向下执行，setTimeout推入待执行队列
    if (!this.data.msg) {
      return
    }
    this.data.valid = false;
    this.setData({
      send: false
    })
    this.send(1, '', true)
    setTimeout(() => {
      console.log('按钮点击');
      this.data.valid = true; // 在定时器未执行前，valid为false,所以点击方法会直接return
    }, 1000)
  },
  delete() {
    if (!this.data.msg) {
      return false
    }
    let number = 1;
    console.log(this.data.cursor);
    if (this.data.msg.length > 1 && this.data.cursor > 1) {
      console.log(this.data.msg.substr(this.data.cursor - 2, 2));
      number = this.data.msg.substr(this.data.cursor - 2, 2).search(/(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f])|(\ud83d[\ude80-\udeff])/i) == -1 ? 1 : 2;
      console.log(number);
      // console.log(this.data.msg.substr(0, this.data.cursor - number));
      // console.log(this.data.msg.substr(this.data.cursor, this.data.msg.length));

      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - number) + this.data.msg.substr(this.data.cursor, this.data.msg.length - this.data.cursor),
        cursor: this.data.cursor - number
      })
    } else if (this.data.cursor == 1) {
      console.log(this.data.cursor, 'cursor');
      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - 1) + this.data.msg.substr(this.data.cursor, this.data.msg.length),
        cursor: this.data.cursor - 1,
      })
    } else {
      console.log('不删');
    }
  },
  // 发送消息
  async send(type, img, flag) {
    console.log(this.data.msg);

    this.setData({
      sendData: ''
    })
    if (type == 1) {
      if (this.data.msg == '') {
        this.setData({
          msg: '',
          footer_bottom: 20
        })
        wx.showToast({
          title: '不能发送空白消息',
          icon: 'none'
        })
        return false
      }
      this.setData({
        sendData: {
          "action": "inc",
          "content": this.data.msg,
          "contentType": 1
        }
      })

    } else if (type == 2) {

      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": img,
          "contentType": 2
        }
      })

    } else {
      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": this.data.goodsImg,
          "content": this.data.goodsContext,
          "contentType": 3
        }
      })
      return
    }
    if (this.data.chatUUID) {
      this.setData({
        ["sendData.chatUUID"]: this.data.chatUUID
      })
      console.log(this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997",
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })
      console.log(code, data, errorMsg, '111');
      if (code == 1) {
        this.setData({
          shopShow: false
        })
        if (type == 1) {
          // let falseData = {
          //   position: "right",
          // }
          this.setData({
            // page: 1,
            send: true,
            msg: '',
            footer_bottom: 20,
          })
        }
        console.log(this.data.sendData);
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg
        })
      }
    } else {
      // 通过传过来的手机号 
      this.setData({
        ["sendData.targetMobile"]: this.data.serveMobile
      })
      console.log('发送', this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997"+"/" + chatUUID
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })

      console.log(data, code, errorMsg);
      if (code == 1) {
        this.setData({
          chatUUID: data
        })
        if (type != 3) {
          this.setData({
            // page: 1,
            msg: '',
            // footer_bottom: 20,
            shopShow: false
          })
        }
        if (type == 1) {
          this.setData({
            footer_bottom: 20,
          })
        }
        // this.getList()
        this.setTiming() //设置定时器
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg,
        })
      }
    }
  },
  delete() {
    if (!this.data.msg) {
      return false
    }
    let number = 1;
    console.log(this.data.cursor);
    if (this.data.msg.length > 1 && this.data.cursor > 1) {
      console.log(this.data.msg.substr(this.data.cursor - 2, 2));
      number = this.data.msg.substr(this.data.cursor - 2, 2).search(/(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f])|(\ud83d[\ude80-\udeff])/i) == -1 ? 1 : 2;
      console.log(number);
      // console.log(this.data.msg.substr(0, this.data.cursor - number));
      // console.log(this.data.msg.substr(this.data.cursor, this.data.msg.length));

      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - number) + this.data.msg.substr(this.data.cursor, this.data.msg.length - this.data.cursor),
        cursor: this.data.cursor - number
      })
    } else if (this.data.cursor == 1) {
      console.log(this.data.cursor, 'cursor');
      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - 1) + this.data.msg.substr(this.data.cursor, this.data.msg.length),
        cursor: this.data.cursor - 1,
      })
    } else {
      console.log('不删');
    }
  },
  // 发送消息
  async send(type, img, flag) {
    console.log(this.data.msg);

    this.setData({
      sendData: ''
    })
    if (type == 1) {
      if (this.data.msg == '') {
        this.setData({
          msg: '',
          footer_bottom: 20
        })
        wx.showToast({
          title: '不能发送空白消息',
          icon: 'none'
        })
        return false
      }
      this.setData({
        sendData: {
          "action": "inc",
          "content": this.data.msg,
          "contentType": 1
        }
      })

    } else if (type == 2) {

      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": img,
          "contentType": 2
        }
      })

    } else {
      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": this.data.goodsImg,
          "content": this.data.goodsContext,
          "contentType": 3
        }
      })
    }
    if (this.data.chatUUID) {
      this.setData({
        ["sendData.chatUUID"]: this.data.chatUUID
      })
      console.log(this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997",
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })
      console.log(code, data, errorMsg, '111');
      if (code == 1) {
        this.setData({
          shopShow: false
        })
        if (type == 1) {
          // let falseData = {
          //   position: "right",
          // }
          this.setData({
            // page: 1,
            send: true,
            msg: '',
            footer_bottom: 20,
          })
        }
        console.log(this.data.sendData);
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg
        })
      }
    } else {
      // 通过传过来的手机号 
      this.setData({
        ["sendData.targetMobile"]: this.data.serveMobile
      })
      console.log('发送', this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997"+"/" + chatUUID
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })

      console.log(data, code, errorMsg);
      if (code == 1) {
        this.setData({
          chatUUID: data
        })
        if (type != 3) {
          this.setData({
            // page: 1,
            msg: '',
            // footer_bottom: 20,
            shopShow: false
          })
        }
        if (type == 1) {
          this.setData({
            footer_bottom: 20,
          })
        }
        // this.getList()
        this.setTiming() //设置定时器
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg,
        })
      }
    }
  },
  delete() {
    if (!this.data.msg) {
      return false
    }
    let number = 1;
    console.log(this.data.cursor);
    if (this.data.msg.length > 1 && this.data.cursor > 1) {
      console.log(this.data.msg.substr(this.data.cursor - 2, 2));
      number = this.data.msg.substr(this.data.cursor - 2, 2).search(/(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f])|(\ud83d[\ude80-\udeff])/i) == -1 ? 1 : 2;
      console.log(number);
      // console.log(this.data.msg.substr(0, this.data.cursor - number));
      // console.log(this.data.msg.substr(this.data.cursor, this.data.msg.length));

      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - number) + this.data.msg.substr(this.data.cursor, this.data.msg.length - this.data.cursor),
        cursor: this.data.cursor - number
      })
    } else if (this.data.cursor == 1) {
      console.log(this.data.cursor, 'cursor');
      this.setData({
        msg: this.data.msg.substr(0, this.data.cursor - 1) + this.data.msg.substr(this.data.cursor, this.data.msg.length),
        cursor: this.data.cursor - 1,
      })
    } else {
      console.log('不删');
    }
  },
  // 发送消息
  async send(type, img, flag) {
    console.log(this.data.msg);

    this.setData({
      sendData: ''
    })
    if (type == 1) {
      if (this.data.msg == '') {
        this.setData({
          msg: '',
          footer_bottom: 20
        })
        wx.showToast({
          title: '不能发送空白消息',
          icon: 'none'
        })
        return false
      }
      this.setData({
        sendData: {
          "action": "inc",
          "content": this.data.msg,
          "contentType": 1
        }
      })

    } else if (type == 2) {

      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": img,
          "contentType": 2
        }
      })

    } else {
      this.setData({
        sendData: {
          "action": "inc",
          "contentImage": this.data.goodsImg,
          "content": this.data.goodsContext,
          "contentType": 3
        }
      })
    }
    if (this.data.chatUUID) {
      this.setData({
        ["sendData.chatUUID"]: this.data.chatUUID
      })
      console.log(this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997",
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })
      console.log(code, data, errorMsg, '111');
      if (code == 1) {
        this.setData({
          shopShow: false
        })
        if (type == 1) {
          // let falseData = {
          //   position: "right",
          // }
          this.setData({
            // page: 1,
            send: true,
            msg: '',
            footer_bottom: 20,
          })
        }
        console.log(this.data.sendData);
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg
        })
      }
    } else {
      // 通过传过来的手机号 
      this.setData({
        ["sendData.targetMobile"]: this.data.serveMobile
      })
      console.log('发送', this.data.sendData);
      const {
        data: {
          code,
          errorMsg,
          data
        }
      } = await wx.cloud.callContainer({
        "config": {
          "env": "prod-0g38oh8hf0e4d5ac"
        },
        // "path": "/v1/chat/18511581997"+"/" + chatUUID
        "path": "/v1/chat/serv",
        "header": {
          "X-WX-SERVICE": "springboot-069k"
        },
        "method": "PUT",
        "data": this.data.sendData
      })

      console.log(data, code, errorMsg);
      if (code == 1) {
        this.setData({
          chatUUID: data
        })
        if (type != 3) {
          this.setData({
            // page: 1,
            msg: '',
            // footer_bottom: 20,
            shopShow: false
          })
        }
        if (type == 1) {
          this.setData({
            footer_bottom: 20,
          })
        }
        // this.getList()
        this.setTiming() //设置定时器
      } else {
        wx.showToast({
          icon: 'none',
          title: errorMsg,
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  setTiming() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
    let timer = setInterval(() => {
      if (this.data.isSearch && !this.data.end) {
        this.serchContext()
      } else {
        this.context(2)
      }
    }, 1000)
    this.setData({
      timer
    })
  },

  // 扩展功能 1：调用相册  2 拍摄
  extendClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    console.log(id);
    if (id == 1) {
      var _this = this;

      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          console.log(res.tempFilePaths);
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          let tempFilePaths = res.tempFilePaths;
          _this.upload(tempFilePaths);

        }

      })

    } else if (id == 2) {

      var _this = this;

      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          console.log(res.tempFilePaths);
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          let tempFilePaths = res.tempFilePaths;
          _this.upload(tempFilePaths);
        }

      })
    }
  },

  emojiClick(e) {
    let {
      item
    } = e.currentTarget.dataset
    console.log(this.data.cursor);
    let msg = this.insertStr(this.data.msg, this.data.cursor, item)
    this.setData({
      msg,
      cursor: this.data.cursor + 2
    })
  },
  upload(path) { // 上传图片
    let that = this;
    // let snapshotPics = that.data.snapshotPics
    wx.showToast({
      icon: "loading",
      title: "正在发送……"
    });
    for (var i = 0; i < path.length; i++) {
      wx.uploadFile({
        url: 'https://talent.199.nuomayun.com/api/order/upload', //后端接口
        filePath: path[i],
        name: 'file',
        formData: {
          user: 'test'
        },
        header: {
          'content-type': 'multipart/form-data'
        },
        success(res) {
          var data = JSON.parse(res.data)
          console.log(data, '看下data是个啥')
          // snapshotPics.push(data.data) 
          // if(data.data&&data.data[0]){
          that.send(2, data.data)
          // }
        },
        fail(e) {
          wx.showModal({
            title: '提示',
            content: '第' + i + '张图片上传失败',
            showCancel: false
          });
        },
        complete() {
          wx.hideToast(); //隐藏Toast
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // console.log('隐藏');
    // if (this.data.timer) {
    //   console.log('卸载定时器');
    //   clearInterval(this.data.timer);
    //   this.setData({
    //     timer: null
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('卸载');
    if (this.data.timer) {
      console.log('卸载定时器');
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
    }
  }
})